﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Threading;
using com.fukefu.source;
using com.fukefu.sql;
using com.fukefu.tools;

namespace com.fukefu.info
{
    public class InformationFactory
    {
        //显示窗体
        public event MyDelegate3 SetControl;
        //修改显示数据
        public event MyDelegate2_1 _UpdateData;
        //数据库连接
        protected SqlServerOperate sql = new SqlServerOperate();
        //锁定
        protected object sync = new object();
        public string vcode = "";
        //集合
        HashSet<string> hs = new HashSet<string>();

        public void Add(string name)
        {
            lock (hs)
            {
                if (!hs.Contains(name))
                {
                    hs.Add(name);
                    new Thread(new ParameterizedThreadStart(Start)).Start(name);
                }
            }
        }
        //开启一个线程
        public void Start(object name)
        {
            int okTimes = 0, errorTime = 0;
            Site site = new SiteCollection().GetSiteByName(name.ToString());
            if (site != null)
            {
                Type t = Type.GetType(site.ClassName);
                if (t == null)
                {
                    Display(name.ToString(), site.ClassName + " 类不存在");
                    return;
                }
                Information b2b = (Information)Activator.CreateInstance(t);
                b2b.Site = site;
                Display(name.ToString(), "开始初始化");
                //标题
                Title title;
                TitleCollection tc = new TitleCollection();
                tc.InitSite(site);
                //用户
                User user;
                UserCollection uc = new UserCollection(site);
                InformationResult info;
                while ((user = uc.Get()) != null)
                {
                    Display(name.ToString(), user.Name + " 开始登陆");
                    if (Login(b2b, site, user))
                    {
                        Display(name.ToString(), user.Name + " 登陆成功,开始发布");
                        while (tc.Count > 0)
                        {
                            //判断关键字是否合格，不合格，自动下一个, 若为空，退出
                            while ((title = tc.Get()) != null && !b2b.CheckKeyword(title)) ;
                            //处理返回结果
                            if (title == null)
                            {
                                Display(name.ToString(), "发布结束,暂无关键字");
                                return;
                            }
                            info = PostArticle(b2b, site, title);
                            //更新显示数据
                            if (info.Code == 1)
                            {
                                okTimes++;
                            }
                            else
                            {
                                errorTime++;
                            }
                            UpdateData(name.ToString(), new string[] { errorTime.ToString(), okTimes.ToString() });
                            //处理结果
                            ProcessResultHtml(site, user, title, info);
                            if (info.Code == 2 || info.Code == 3)
                            {
                                break;
                            }
                        }
                        Display(name.ToString(), user.Name + " 发布结束");
                    }
                    else
                    {
                        Display(name.ToString(), user.Name + " 登陆失败");
                    }
                    //切换用户,清理cookie
                    CookieFactory.GetInstance().Clear("." + site.Domain);
                }
                Display(name.ToString(), "发布结束");
            }
            else
            {
                Display(name.ToString(), "暂无该网站账号");
            }
            Display(name.ToString(), "----------------------");
            hs.Remove(name.ToString());
        }
        //登陆
        private bool Login(Information b2b, Site site, User user)
        {
            if (site.LoginVcode)
            {
                return b2b.Login(user, GetVerificationCode(b2b.GetFlushCodeImage()));
            }
            else
            {
                return b2b.Login(user);
            }
        }
        //发布文章
        private InformationResult PostArticle(Information b2b, Site site, Title title)
        {
            if (site.PostVcode)
            {
                return b2b.PostArticle(title, GetVerificationCode(b2b.GetFlushCodeImage()));
            }
            else
            {
                return b2b.PostArticle(title);
            }
        }
        //处理返回结果
        private void ProcessResultHtml(Site site, User user, Title title, InformationResult info)
        {
            string mess = info.Content;
            if (info.Code == 1)
            {
                SaveArticle(info.Content, title.KId, user.Uid);
                mess = title.Word + " 发布成功";
            }
            Display(site.Title, user.Name + " " + mess);
            //判断账户是否继续发布
            if (info.Code == 2)
            {
                user.StopUsing();
            }
            Thread.Sleep(site.SleepTime);
        }
        //获取验证码
        private string GetVerificationCode(Image iamge)
        {
            string code = "";
            lock (sync)
            {
                vcode = "";
                ShowVerificationCode(iamge);
                SetButton(true);
                while (vcode.Equals(""))
                {
                    Thread.Sleep(100);
                }
                code = vcode;
                SetTextBoxText("");
            }
            return code;
        }
        //存储已发布文章
        protected void SaveArticle(string url, string tid, string uid)
        {
            string[] _url = url.Split('|');
            foreach (string s in _url)
            {
                if (s.StartsWith("http://"))
                {
                    sql.Update("insert into [已发布](url,titleid,uid) values('" + s + "','" + tid + "','" + uid + "')");
                }
            }
        }
        //显示数据
        private void UpdateData(string value, string[] str)
        {
            if (_UpdateData != null)
            {
                _UpdateData(value, str);
            }
        }
        //显示信息
        protected void Display(string name, string message)
        {
            SetControl(name, ControlValue.ListBox, DateTime.Now.ToString("hh:mm:ss") + " " + message);
        }
        //显示验证码
        private void ShowVerificationCode(object obj1)
        {
            SetControl("vcode", ControlValue.PictureBox, obj1);
        }
        //设置按钮
        private void SetButton(object obj2)
        {
            SetControl("button1", ControlValue.Enable, obj2);
        }
        //设置文本框字体
        private void SetTextBoxText(object obj2)
        {
            SetControl("textbox1", ControlValue.Text, obj2);
        }
    }
}
